from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from starlette.middleware.base import BaseHTTPMiddleware

class MyMiddleWare(BaseHTTPMiddleware):
    async def dispatch(self, req, call_next):
        # 前置操作
        resp = await call_next(req)
        # 后置操作
        return resp


def register_middleware(app:FastAPI):
    # 跨域设置（浏览器的安全机制）
    app.add_middleware(
        CORSMiddleware,
        allow_origins="*",
        allow_credentials=True,
        allow_methods=["GET", "POST"],
        allow_headers=["*"],
    )
    # 设置host列表
    app.add_middleware(TrustedHostMiddleware, allowed_hosts=['127.0.0.1'])
    # 设置数据压缩
    app.add_middleware(GZipMiddleware, minimum_size=100)

    app.add_middleware(MyMiddleWare)